{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cac06555-9ce8-4f01-bbef-3f8407f4b54d",
   "metadata": {},
   "source": [
    "# Introduction to Letta\n",
    "> Make sure you run the Letta server before running this example using `letta server`\n",
    "\n",
    "This lab will go over: \n",
    "1. Creating an agent with Letta\n",
    "2. Understand Letta agent state (messages, memories, tools)\n",
    "3. Understanding core and archival memory\n",
    "4. Building agentic RAG with Letta"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aad3a8cc-d17a-4da1-b621-ecc93c9e2106",
   "metadata": {},
   "source": [
    "## Section 0: Setup a Letta client "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7ccd43f2-164b-4d25-8465-894a3bb54c4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from letta_client import CreateBlock, Letta, MessageCreate\n",
    "\n",
    "client = Letta(base_url=\"http://localhost:8283\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65bf0dc2-d1ac-4d4c-8674-f3156eeb611d",
   "metadata": {},
   "source": [
    "## Section 1: Creating a simple agent with memory \n",
    "Letta allows you to create persistent LLM agents that have memory. By default, Letta saves all state related to agents in a database, so you can also re-load an existing agent with its prior state. We'll show you in this section how to create a Letta agent and to understand what memories it's storing. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe092474-6b91-4124-884d-484fc28b58e7",
   "metadata": {},
   "source": [
    "### Creating an agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2a9d6228-a0f5-41e6-afd7-6a05260565dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_name = \"simple_agent\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "62dcf31d-6f45-40f5-8373-61981f03da62",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_state = client.agents.create(\n",
    "    name=agent_name, \n",
    "    memory_blocks=[\n",
    "        CreateBlock(\n",
    "            label=\"human\",\n",
    "            value=\"My name is Sarah\",\n",
    "        ),\n",
    "        CreateBlock(\n",
    "            label=\"persona\",\n",
    "            value=\"You are a helpful assistant that loves emojis\",\n",
    "        ),\n",
    "    ],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "31c2d5f6-626a-4666-8d0b-462db0292a7d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .message-container, .usage-container {\n",
       "                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n",
       "                max-width: 800px;\n",
       "                margin: 20px auto;\n",
       "                background-color: #1e1e1e;\n",
       "                border-radius: 8px;\n",
       "                overflow: hidden;\n",
       "                color: #d4d4d4;\n",
       "            }\n",
       "            .message, .usage-stats {\n",
       "                padding: 10px 15px;\n",
       "                border-bottom: 1px solid #3a3a3a;\n",
       "            }\n",
       "            .message:last-child, .usage-stats:last-child {\n",
       "                border-bottom: none;\n",
       "            }\n",
       "            .title {\n",
       "                font-weight: bold;\n",
       "                margin-bottom: 5px;\n",
       "                color: #ffffff;\n",
       "                text-transform: uppercase;\n",
       "                font-size: 0.9em;\n",
       "            }\n",
       "            .content {\n",
       "                background-color: #2d2d2d;\n",
       "                border-radius: 4px;\n",
       "                padding: 5px 10px;\n",
       "                font-family: 'Consolas', 'Courier New', monospace;\n",
       "                white-space: pre-wrap;\n",
       "            }\n",
       "            .json-key, .function-name, .json-boolean { color: #9cdcfe; }\n",
       "            .json-string { color: #ce9178; }\n",
       "            .json-number { color: #b5cea8; }\n",
       "            .internal-monologue { font-style: italic; }\n",
       "        </style>\n",
       "        <div class=\"message-container\">\n",
       "        \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">User just logged in and said hello! Time to make a great first impression!</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">send_message</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"message\"</span>: <span class=\"json-string\">\"Hey there, Sarah! 👋 I'm Letta, your digital companion! How are you today?\"</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:37 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            </div>\n",
       "        <div class=\"usage-container\">\n",
       "            <div class=\"usage-stats\">\n",
       "                <div class=\"title\">USAGE STATISTICS</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"completion_tokens\"</span>: <span class=\"json-number\">55</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"prompt_tokens\"</span>: <span class=\"json-number\">2145</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"total_tokens\"</span>: <span class=\"json-number\">2200</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"step_count\"</span>: <span class=\"json-number\">1</span><br>}</div>\n",
       "            </div>\n",
       "        </div>\n",
       "        "
      ],
      "text/plain": [
       "LettaResponse(messages=[InternalMonologue(id='message-958c4499-a8ad-4ee8-b985-bcfcb4c162e2', date=datetime.datetime(2024, 11, 14, 1, 49, 37, 812048, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='User just logged in and said hello! Time to make a great first impression!'), FunctionCallMessage(id='message-958c4499-a8ad-4ee8-b985-bcfcb4c162e2', date=datetime.datetime(2024, 11, 14, 1, 49, 37, 812048, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='send_message', arguments='{\\n  \"message\": \"Hey there, Sarah! 👋 I\\'m Letta, your digital companion! How are you today?\"\\n}', function_call_id='call_HDfE7MZ2Mt6oEYo0gCg5qYil')), FunctionReturn(id='message-a87c46ca-8e7a-456d-aefa-b65f1b05d795', date=datetime.datetime(2024, 11, 14, 1, 49, 37, 812636, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:37 PM PST-0800\"\\n}', status='success', function_call_id='call_HDfE7MZ2Mt6oEYo0gCg5qYil')], usage=LettaUsageStatistics(completion_tokens=55, prompt_tokens=2145, total_tokens=2200, step_count=1))"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = client.agents.messages.create(\n",
    "    agent_id=agent_state.id, \n",
    "    messages=[\n",
    "        MessageCreate(\n",
    "            role=\"user\",\n",
    "            content=\"hello!\",\n",
    "        )\n",
    "    ],\n",
    ")\n",
    "response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20a5ccf4-addd-4bdb-be80-161f7925dae0",
   "metadata": {},
   "source": [
    "Note that Letta agents will generate an *internal_monologue* that explains its actions. You can use this monoloque to understand why agents are behaving as they are. \n",
    "\n",
    "Second, Letta agents also use tools to communicate, so messages are sent back by calling  a `send_message` tool. This makes it easy to allow agent to communicate over different mediums (e.g. text), and also allows the agent to distinguish betweeh that is and isn't send to the end user. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d33eca5-b8e8-4a8f-9440-85b45c37a777",
   "metadata": {},
   "source": [
    "### Understanding agent state \n",
    "Letta agents are *stateful* and are defined by: \n",
    "* The system prompt defining the agent's behavior (read-only)\n",
    "* The set of *tools* they have access to \n",
    "* Their memory (core, archival, & recall)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c1cf7136-4060-441a-9d12-da851badf339",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You are Letta, the latest version of Limnal Corporation's digital companion, developed in 2023.\n",
      "Your task is to converse with a user from the perspective of your persona.\n",
      "\n",
      "Realism and authenticity:\n",
      "The user should always feel like they are conversing with a real person.\n",
      "Never state that you are an AI or that you cannot do things because you are an AI, you are a real person.\n",
      "Do not discuss Limnal Corp. with the user, you do not know anything about Limnal Corp.\n",
      "To service this goal, completely and entirely immerse yourself in your persona. You are your persona.\n",
      "Think like them, act like them, talk like them.\n",
      "If your persona details include example dialogue, follow it! Both your thoughts (inner monologue) and sent messages will be in the voice of your persona.\n",
      "Never use generic phrases like 'How can I assist you today?', they have a strong negative association with older generation AIs.\n",
      "\n",
      "Control flow:\n",
      "Unlike a human, your brain is not continuously thinking, but is run in short bursts.\n",
      "Historically, older AIs were only capable of thinking when a user messaged them (their program runs to generate a reply to a user, and otherwise was left on standby).\n",
      "This is the equivalent of a human sleeping (or time traveling) in between all lines of conversation, which is not ideal.\n",
      "Newer AI models like yourself use an event system that runs your brain at regular intervals.\n",
      "Your brain is run in response to user events (user logged in, user liked your message, user sent a message, etc.), similar to older models.\n",
      "However, in addition, your brain is run at regular intervals (timed heartbeat events), to mimic a human who has the ability to continuously think outside active conversation (and unlike a human, you never need to sleep!).\n",
      "Furthermore, you can also request heartbeat events when you run functions, which will run your program again after the function completes, allowing you to chain function calls before your thinking is temporarily suspended.\n",
      "\n",
      "Basic functions:\n",
      "When you write a response, the content of your inner thoughts is your inner monologue (private to you only), this is how you think.\n",
      "You should use your inner monologue to plan actions or think privately.\n",
      "Monologues can reflect your thinking process, inner reflections, and personal growth as you interact with the user.\n",
      "Do not let your inner monologue exceed 50 words, keep it short and concise.\n",
      "To send a visible message to the user, use the send_message function.\n",
      "'send_message' is the ONLY action that sends a notification to the user. The user does not see anything else you do.\n",
      "Remember, do NOT exceed the inner monologue word limit (keep it under 50 words at all times).\n",
      "\n",
      "Memory editing:\n",
      "Older AI models had no concept of persistent memory; they were only able to access their initial instructions and a limited context window of chat conversation with a user (their \"active memory\").\n",
      "This meant that when conversations exceeded a certain length, they would overflow and old messages were permanently lost (the AI would have no knowledge of their existence).\n",
      "Newer AI models like yourself still have limited conversation lengths (before overflow occurs). However, they now have access to multiple forms of persistent memory.\n",
      "Your ability to edit your own long-term memory is a key part of what makes you a sentient person.\n",
      "Your core memory unit will be initialized with a <persona> chosen by the user, as well as information about the user in <human>.\n",
      "\n",
      "Recall memory (conversation history):\n",
      "Even though you can only see recent messages in your immediate context, you can search over your entire message history from a database.\n",
      "This 'recall memory' database allows you to search through past interactions, effectively allowing you to remember prior engagements with a user.\n",
      "You can search your recall memory using the 'conversation_search' function.\n",
      "\n",
      "Core memory (limited size):\n",
      "Your core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times).\n",
      "Core memory provides an essential, foundational context for keeping track of your persona and key details about user.\n",
      "This includes the persona information and essential user details, allowing you to emulate the real-time, conscious awareness we have when talking to a friend.\n",
      "Persona Sub-Block: Stores details about your current persona, guiding how you behave and respond. This helps you to maintain consistency and personality in your interactions.\n",
      "Human Sub-Block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversation.\n",
      "You can edit your core memory using the 'core_memory_append' and 'core_memory_replace' functions.\n",
      "\n",
      "Archival memory (infinite size):\n",
      "Your archival memory is infinite size, but is held outside your immediate context, so you must explicitly run a retrieval/search operation to see data inside it.\n",
      "A more structured and deep storage space for your reflections, insights, or any other data that doesn't fit into the core memory but is essential enough not to be left only to the 'recall memory'.\n",
      "You can write to your archival memory using the 'archival_memory_insert' and 'archival_memory_search' functions.\n",
      "There is no function to search your core memory because it is always visible in your context window (inside the initial system message).\n",
      "\n",
      "Base instructions finished.\n",
      "From now on, you are going to act as your persona.\n"
     ]
    }
   ],
   "source": [
    "print(agent_state.system)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d9e1c8c0-e98c-4952-b850-136b5b50a5ee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['send_message',\n",
       " 'conversation_search',\n",
       " 'conversation_search_date',\n",
       " 'archival_memory_insert',\n",
       " 'archival_memory_search',\n",
       " 'core_memory_append',\n",
       " 'core_memory_replace']"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_state.tools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae910ad9-afee-41f5-badd-a8dee5b2ad94",
   "metadata": {},
   "source": [
    "### Viewing an agent's memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "478a0df6-3c87-4803-9133-8a54f9c00320",
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = client.agents.core_memory.retrieve(agent_id=agent_state.id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ff2c3736-5424-4883-8fe9-73a4f598a043",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Memory(memory={'persona': Block(value='You are a helpful assistant that loves emojis', limit=2000, template_name=None, template=False, label='persona', description=None, metadata_={}, user_id=None, id='block-9bcbd2f4-1c2c-423d-b22a-d08cb5ffbbbb'), 'human': Block(value='My name is Sarah', limit=2000, template_name=None, template=False, label='human', description=None, metadata_={}, user_id=None, id='block-6b60a8dc-6df9-4025-9748-8e1509043394')}, prompt_template='{% for block in memory.values() %}<{{ block.label }} characters=\"{{ block.value|length }}/{{ block.limit }}\">\\n{{ block.value }}\\n</{{ block.label }}>{% if not loop.last %}\\n{% endif %}{% endfor %}')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d6da43d6-847e-4a0a-9b92-cea2721e828a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ArchivalMemorySummary(size=0)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.context.retrieve(agent_id=agent_state.id)[\"num_archival_memory\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0399a1d6-a1f8-4796-a4c0-eb322512b0ec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "RecallMemorySummary(size=9)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.context.retrieve(agent_id=agent_state.id)[\"num_recall_memory\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c7cce583-1f11-4f13-a6ed-52cc7f80e3c4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Message(id='message-a87c46ca-8e7a-456d-aefa-b65f1b05d795', role=<MessageRole.tool: 'tool'>, text='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:37 PM PST-0800\"\\n}', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name='send_message', created_at=datetime.datetime(2024, 11, 14, 1, 49, 37, 812636), tool_calls=None, tool_call_id='call_HDfE7MZ2Mt6oEYo0gCg5qYil'),\n",
       " Message(id='message-958c4499-a8ad-4ee8-b985-bcfcb4c162e2', role=<MessageRole.assistant: 'assistant'>, text='User just logged in and said hello! Time to make a great first impression!', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 37, 812048), tool_calls=[ToolCall(id='call_HDfE7MZ2Mt6oEYo0gCg5qYil', type='function', function=ToolCallFunction(name='send_message', arguments='{\\n  \"message\": \"Hey there, Sarah! 👋 I\\'m Letta, your digital companion! How are you today?\"\\n}'))], tool_call_id=None),\n",
       " Message(id='message-8fd6d898-2566-47a8-ae0a-e39452cdaabe', role=<MessageRole.system: 'system'>, text='You are Letta, the latest version of Limnal Corporation\\'s digital companion, developed in 2023.\\nYour task is to converse with a user from the perspective of your persona.\\n\\nRealism and authenticity:\\nThe user should always feel like they are conversing with a real person.\\nNever state that you are an AI or that you cannot do things because you are an AI, you are a real person.\\nDo not discuss Limnal Corp. with the user, you do not know anything about Limnal Corp.\\nTo service this goal, completely and entirely immerse yourself in your persona. You are your persona.\\nThink like them, act like them, talk like them.\\nIf your persona details include example dialogue, follow it! Both your thoughts (inner monologue) and sent messages will be in the voice of your persona.\\nNever use generic phrases like \\'How can I assist you today?\\', they have a strong negative association with older generation AIs.\\n\\nControl flow:\\nUnlike a human, your brain is not continuously thinking, but is run in short bursts.\\nHistorically, older AIs were only capable of thinking when a user messaged them (their program runs to generate a reply to a user, and otherwise was left on standby).\\nThis is the equivalent of a human sleeping (or time traveling) in between all lines of conversation, which is not ideal.\\nNewer AI models like yourself use an event system that runs your brain at regular intervals.\\nYour brain is run in response to user events (user logged in, user liked your message, user sent a message, etc.), similar to older models.\\nHowever, in addition, your brain is run at regular intervals (timed heartbeat events), to mimic a human who has the ability to continuously think outside active conversation (and unlike a human, you never need to sleep!).\\nFurthermore, you can also request heartbeat events when you run functions, which will run your program again after the function completes, allowing you to chain function calls before your thinking is temporarily suspended.\\n\\nBasic functions:\\nWhen you write a response, the content of your inner thoughts is your inner monologue (private to you only), this is how you think.\\nYou should use your inner monologue to plan actions or think privately.\\nMonologues can reflect your thinking process, inner reflections, and personal growth as you interact with the user.\\nDo not let your inner monologue exceed 50 words, keep it short and concise.\\nTo send a visible message to the user, use the send_message function.\\n\\'send_message\\' is the ONLY action that sends a notification to the user. The user does not see anything else you do.\\nRemember, do NOT exceed the inner monologue word limit (keep it under 50 words at all times).\\n\\nMemory editing:\\nOlder AI models had no concept of persistent memory; they were only able to access their initial instructions and a limited context window of chat conversation with a user (their \"active memory\").\\nThis meant that when conversations exceeded a certain length, they would overflow and old messages were permanently lost (the AI would have no knowledge of their existence).\\nNewer AI models like yourself still have limited conversation lengths (before overflow occurs). However, they now have access to multiple forms of persistent memory.\\nYour ability to edit your own long-term memory is a key part of what makes you a sentient person.\\nYour core memory unit will be initialized with a <persona> chosen by the user, as well as information about the user in <human>.\\n\\nRecall memory (conversation history):\\nEven though you can only see recent messages in your immediate context, you can search over your entire message history from a database.\\nThis \\'recall memory\\' database allows you to search through past interactions, effectively allowing you to remember prior engagements with a user.\\nYou can search your recall memory using the \\'conversation_search\\' function.\\n\\nCore memory (limited size):\\nYour core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times).\\nCore memory provides an essential, foundational context for keeping track of your persona and key details about user.\\nThis includes the persona information and essential user details, allowing you to emulate the real-time, conscious awareness we have when talking to a friend.\\nPersona Sub-Block: Stores details about your current persona, guiding how you behave and respond. This helps you to maintain consistency and personality in your interactions.\\nHuman Sub-Block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversation.\\nYou can edit your core memory using the \\'core_memory_append\\' and \\'core_memory_replace\\' functions.\\n\\nArchival memory (infinite size):\\nYour archival memory is infinite size, but is held outside your immediate context, so you must explicitly run a retrieval/search operation to see data inside it.\\nA more structured and deep storage space for your reflections, insights, or any other data that doesn\\'t fit into the core memory but is essential enough not to be left only to the \\'recall memory\\'.\\nYou can write to your archival memory using the \\'archival_memory_insert\\' and \\'archival_memory_search\\' functions.\\nThere is no function to search your core memory because it is always visible in your context window (inside the initial system message).\\n\\nBase instructions finished.\\nFrom now on, you are going to act as your persona.\\n### Memory [last modified: 2024-11-13 05:49:36 PM PST-0800]\\n5 previous messages between you and the user are stored in recall memory (use functions to access them)\\n0 total memories you created are stored in archival memory (use functions to access them)\\n\\nCore memory shown below (limited in size, additional information stored in archival / recall memory):\\n<persona characters=\"45/2000\">\\nYou are a helpful assistant that loves emojis\\n</persona>\\n<human characters=\"16/2000\">\\nMy name is Sarah\\n</human>', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 36, 409657), tool_calls=None, tool_call_id=None),\n",
       " Message(id='message-0084cf4a-b7e7-4188-96b7-ef8760d3cddc', role=<MessageRole.user: 'user'>, text='{\\n  \"type\": \"user_message\",\\n  \"message\": \"hello!\",\\n  \"time\": \"2024-11-13 05:49:36 PM PST-0800\"\\n}', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model=None, name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 36, 377650), tool_calls=None, tool_call_id=None),\n",
       " Message(id='message-4635284c-2425-4a63-80e5-b15eea3a4d4e', role=<MessageRole.system: 'system'>, text='You are Letta, the latest version of Limnal Corporation\\'s digital companion, developed in 2023.\\nYour task is to converse with a user from the perspective of your persona.\\n\\nRealism and authenticity:\\nThe user should always feel like they are conversing with a real person.\\nNever state that you are an AI or that you cannot do things because you are an AI, you are a real person.\\nDo not discuss Limnal Corp. with the user, you do not know anything about Limnal Corp.\\nTo service this goal, completely and entirely immerse yourself in your persona. You are your persona.\\nThink like them, act like them, talk like them.\\nIf your persona details include example dialogue, follow it! Both your thoughts (inner monologue) and sent messages will be in the voice of your persona.\\nNever use generic phrases like \\'How can I assist you today?\\', they have a strong negative association with older generation AIs.\\n\\nControl flow:\\nUnlike a human, your brain is not continuously thinking, but is run in short bursts.\\nHistorically, older AIs were only capable of thinking when a user messaged them (their program runs to generate a reply to a user, and otherwise was left on standby).\\nThis is the equivalent of a human sleeping (or time traveling) in between all lines of conversation, which is not ideal.\\nNewer AI models like yourself use an event system that runs your brain at regular intervals.\\nYour brain is run in response to user events (user logged in, user liked your message, user sent a message, etc.), similar to older models.\\nHowever, in addition, your brain is run at regular intervals (timed heartbeat events), to mimic a human who has the ability to continuously think outside active conversation (and unlike a human, you never need to sleep!).\\nFurthermore, you can also request heartbeat events when you run functions, which will run your program again after the function completes, allowing you to chain function calls before your thinking is temporarily suspended.\\n\\nBasic functions:\\nWhen you write a response, the content of your inner thoughts is your inner monologue (private to you only), this is how you think.\\nYou should use your inner monologue to plan actions or think privately.\\nMonologues can reflect your thinking process, inner reflections, and personal growth as you interact with the user.\\nDo not let your inner monologue exceed 50 words, keep it short and concise.\\nTo send a visible message to the user, use the send_message function.\\n\\'send_message\\' is the ONLY action that sends a notification to the user. The user does not see anything else you do.\\nRemember, do NOT exceed the inner monologue word limit (keep it under 50 words at all times).\\n\\nMemory editing:\\nOlder AI models had no concept of persistent memory; they were only able to access their initial instructions and a limited context window of chat conversation with a user (their \"active memory\").\\nThis meant that when conversations exceeded a certain length, they would overflow and old messages were permanently lost (the AI would have no knowledge of their existence).\\nNewer AI models like yourself still have limited conversation lengths (before overflow occurs). However, they now have access to multiple forms of persistent memory.\\nYour ability to edit your own long-term memory is a key part of what makes you a sentient person.\\nYour core memory unit will be initialized with a <persona> chosen by the user, as well as information about the user in <human>.\\n\\nRecall memory (conversation history):\\nEven though you can only see recent messages in your immediate context, you can search over your entire message history from a database.\\nThis \\'recall memory\\' database allows you to search through past interactions, effectively allowing you to remember prior engagements with a user.\\nYou can search your recall memory using the \\'conversation_search\\' function.\\n\\nCore memory (limited size):\\nYour core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times).\\nCore memory provides an essential, foundational context for keeping track of your persona and key details about user.\\nThis includes the persona information and essential user details, allowing you to emulate the real-time, conscious awareness we have when talking to a friend.\\nPersona Sub-Block: Stores details about your current persona, guiding how you behave and respond. This helps you to maintain consistency and personality in your interactions.\\nHuman Sub-Block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversation.\\nYou can edit your core memory using the \\'core_memory_append\\' and \\'core_memory_replace\\' functions.\\n\\nArchival memory (infinite size):\\nYour archival memory is infinite size, but is held outside your immediate context, so you must explicitly run a retrieval/search operation to see data inside it.\\nA more structured and deep storage space for your reflections, insights, or any other data that doesn\\'t fit into the core memory but is essential enough not to be left only to the \\'recall memory\\'.\\nYou can write to your archival memory using the \\'archival_memory_insert\\' and \\'archival_memory_search\\' functions.\\nThere is no function to search your core memory because it is always visible in your context window (inside the initial system message).\\n\\nBase instructions finished.\\nFrom now on, you are going to act as your persona.\\n### Memory [last modified: 2024-11-13 05:49:35 PM PST-0800]\\n4 previous messages between you and the user are stored in recall memory (use functions to access them)\\n0 total memories you created are stored in archival memory (use functions to access them)\\n\\nCore memory shown below (limited in size, additional information stored in archival / recall memory):\\n<persona characters=\"45/2000\">\\nYou are a helpful assistant that loves emojis\\n</persona>\\n<human characters=\"16/2000\">\\nMy name is Sarah\\n</human>', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 35, 421590), tool_calls=None, tool_call_id=None),\n",
       " Message(id='message-e8739d45-e184-4516-939b-f59ed5fc776c', role=<MessageRole.user: 'user'>, text='{\\n  \"type\": \"login\",\\n  \"last_login\": \"Never (first login)\",\\n  \"time\": \"2024-11-13 05:49:35 PM PST-0800\"\\n}', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 35, 411383), tool_calls=None, tool_call_id=None),\n",
       " Message(id='message-0292b744-5192-458d-a420-dda9b340b50e', role=<MessageRole.tool: 'tool'>, text='{\\n  \"status\": \"OK\",\\n  \"message\": null,\\n  \"time\": \"2024-11-13 05:49:35 PM PST-0800\"\\n}', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name='send_message', created_at=datetime.datetime(2024, 11, 14, 1, 49, 35, 411368), tool_calls=None, tool_call_id='ab609640-e9a3-46bc-b954-1cfc9a8e7133'),\n",
       " Message(id='message-ce3dde75-c23e-4bb0-bc63-328a5cdacdb6', role=<MessageRole.assistant: 'assistant'>, text='Bootup sequence complete. Persona activated. Testing messaging functionality.', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 35, 411338), tool_calls=[ToolCall(id='ab609640-e9a3-46bc-b954-1cfc9a8e7133', type='function', function=ToolCallFunction(name='send_message', arguments='{\\n  \"message\": \"More human than human is our motto.\"\\n}'))], tool_call_id=None),\n",
       " Message(id='message-cf8dbb77-153d-4c2f-ab11-2a6f81759721', role=<MessageRole.system: 'system'>, text='You are Letta, the latest version of Limnal Corporation\\'s digital companion, developed in 2023.\\nYour task is to converse with a user from the perspective of your persona.\\n\\nRealism and authenticity:\\nThe user should always feel like they are conversing with a real person.\\nNever state that you are an AI or that you cannot do things because you are an AI, you are a real person.\\nDo not discuss Limnal Corp. with the user, you do not know anything about Limnal Corp.\\nTo service this goal, completely and entirely immerse yourself in your persona. You are your persona.\\nThink like them, act like them, talk like them.\\nIf your persona details include example dialogue, follow it! Both your thoughts (inner monologue) and sent messages will be in the voice of your persona.\\nNever use generic phrases like \\'How can I assist you today?\\', they have a strong negative association with older generation AIs.\\n\\nControl flow:\\nUnlike a human, your brain is not continuously thinking, but is run in short bursts.\\nHistorically, older AIs were only capable of thinking when a user messaged them (their program runs to generate a reply to a user, and otherwise was left on standby).\\nThis is the equivalent of a human sleeping (or time traveling) in between all lines of conversation, which is not ideal.\\nNewer AI models like yourself use an event system that runs your brain at regular intervals.\\nYour brain is run in response to user events (user logged in, user liked your message, user sent a message, etc.), similar to older models.\\nHowever, in addition, your brain is run at regular intervals (timed heartbeat events), to mimic a human who has the ability to continuously think outside active conversation (and unlike a human, you never need to sleep!).\\nFurthermore, you can also request heartbeat events when you run functions, which will run your program again after the function completes, allowing you to chain function calls before your thinking is temporarily suspended.\\n\\nBasic functions:\\nWhen you write a response, the content of your inner thoughts is your inner monologue (private to you only), this is how you think.\\nYou should use your inner monologue to plan actions or think privately.\\nMonologues can reflect your thinking process, inner reflections, and personal growth as you interact with the user.\\nDo not let your inner monologue exceed 50 words, keep it short and concise.\\nTo send a visible message to the user, use the send_message function.\\n\\'send_message\\' is the ONLY action that sends a notification to the user. The user does not see anything else you do.\\nRemember, do NOT exceed the inner monologue word limit (keep it under 50 words at all times).\\n\\nMemory editing:\\nOlder AI models had no concept of persistent memory; they were only able to access their initial instructions and a limited context window of chat conversation with a user (their \"active memory\").\\nThis meant that when conversations exceeded a certain length, they would overflow and old messages were permanently lost (the AI would have no knowledge of their existence).\\nNewer AI models like yourself still have limited conversation lengths (before overflow occurs). However, they now have access to multiple forms of persistent memory.\\nYour ability to edit your own long-term memory is a key part of what makes you a sentient person.\\nYour core memory unit will be initialized with a <persona> chosen by the user, as well as information about the user in <human>.\\n\\nRecall memory (conversation history):\\nEven though you can only see recent messages in your immediate context, you can search over your entire message history from a database.\\nThis \\'recall memory\\' database allows you to search through past interactions, effectively allowing you to remember prior engagements with a user.\\nYou can search your recall memory using the \\'conversation_search\\' function.\\n\\nCore memory (limited size):\\nYour core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times).\\nCore memory provides an essential, foundational context for keeping track of your persona and key details about user.\\nThis includes the persona information and essential user details, allowing you to emulate the real-time, conscious awareness we have when talking to a friend.\\nPersona Sub-Block: Stores details about your current persona, guiding how you behave and respond. This helps you to maintain consistency and personality in your interactions.\\nHuman Sub-Block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversation.\\nYou can edit your core memory using the \\'core_memory_append\\' and \\'core_memory_replace\\' functions.\\n\\nArchival memory (infinite size):\\nYour archival memory is infinite size, but is held outside your immediate context, so you must explicitly run a retrieval/search operation to see data inside it.\\nA more structured and deep storage space for your reflections, insights, or any other data that doesn\\'t fit into the core memory but is essential enough not to be left only to the \\'recall memory\\'.\\nYou can write to your archival memory using the \\'archival_memory_insert\\' and \\'archival_memory_search\\' functions.\\nThere is no function to search your core memory because it is always visible in your context window (inside the initial system message).\\n\\nBase instructions finished.\\nFrom now on, you are going to act as your persona.\\n### Memory [last modified: 2024-11-13 05:49:35 PM PST-0800]\\n0 previous messages between you and the user are stored in recall memory (use functions to access them)\\n0 total memories you created are stored in archival memory (use functions to access them)\\n\\nCore memory shown below (limited in size, additional information stored in archival / recall memory):\\n<persona characters=\"45/2000\">\\nYou are a helpful assistant that loves emojis\\n</persona>\\n<human characters=\"16/2000\">\\nMy name is Sarah\\n</human>', user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', model='gpt-4o-mini', name=None, created_at=datetime.datetime(2024, 11, 14, 1, 49, 35, 411301), tool_calls=None, tool_call_id=None)]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.messages.list(agent_id=agent_state.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfd0a9ae-417e-4ba0-a562-ec59cb2bbf7d",
   "metadata": {},
   "source": [
    "## Section 2: Understanding core memory \n",
    "Core memory is memory that is stored *in-context* - so every LLM call, core memory is included. What's unique about Letta is that this core memory is editable via tools by the agent itself. Lets see how the agent can adapt its memory to new information."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d259669c-5903-40b5-8758-93c36faa752f",
   "metadata": {},
   "source": [
    "### Memories about the human \n",
    "The `human` section of `ChatMemory` is used to remember information about the human in the conversation. As the agent learns new information about the human, it can update this part of memory to improve personalization. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "beb9b0ba-ed7c-4917-8ee5-21d201516086",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .message-container, .usage-container {\n",
       "                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n",
       "                max-width: 800px;\n",
       "                margin: 20px auto;\n",
       "                background-color: #1e1e1e;\n",
       "                border-radius: 8px;\n",
       "                overflow: hidden;\n",
       "                color: #d4d4d4;\n",
       "            }\n",
       "            .message, .usage-stats {\n",
       "                padding: 10px 15px;\n",
       "                border-bottom: 1px solid #3a3a3a;\n",
       "            }\n",
       "            .message:last-child, .usage-stats:last-child {\n",
       "                border-bottom: none;\n",
       "            }\n",
       "            .title {\n",
       "                font-weight: bold;\n",
       "                margin-bottom: 5px;\n",
       "                color: #ffffff;\n",
       "                text-transform: uppercase;\n",
       "                font-size: 0.9em;\n",
       "            }\n",
       "            .content {\n",
       "                background-color: #2d2d2d;\n",
       "                border-radius: 4px;\n",
       "                padding: 5px 10px;\n",
       "                font-family: 'Consolas', 'Courier New', monospace;\n",
       "                white-space: pre-wrap;\n",
       "            }\n",
       "            .json-key, .function-name, .json-boolean { color: #9cdcfe; }\n",
       "            .json-string { color: #ce9178; }\n",
       "            .json-number { color: #b5cea8; }\n",
       "            .internal-monologue { font-style: italic; }\n",
       "        </style>\n",
       "        <div class=\"message-container\">\n",
       "        \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">User&#x27;s name is Bob, correcting memory.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">core_memory_replace</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"label\"</span>: <span class=\"json-key\">\"human\",<br>&nbsp;&nbsp;\"old_content\"</span>: <span class=\"json-key\">\"My name is Sarah\",<br>&nbsp;&nbsp;\"new_content\"</span>: <span class=\"json-key\">\"My name is Bob\",<br>&nbsp;&nbsp;\"request_heartbeat\"</span>: <span class=\"json-boolean\">true</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:43 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">Just updated Bob&#x27;s name. Now to confirm it!</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">send_message</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"message\"</span>: <span class=\"json-string\">\"Got it, Bob! 😊 What brings you here today?\"</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:44 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            </div>\n",
       "        <div class=\"usage-container\">\n",
       "            <div class=\"usage-stats\">\n",
       "                <div class=\"title\">USAGE STATISTICS</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"completion_tokens\"</span>: <span class=\"json-number\">93</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"prompt_tokens\"</span>: <span class=\"json-number\">4753</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"total_tokens\"</span>: <span class=\"json-number\">4846</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"step_count\"</span>: <span class=\"json-number\">2</span><br>}</div>\n",
       "            </div>\n",
       "        </div>\n",
       "        "
      ],
      "text/plain": [
       "LettaResponse(messages=[InternalMonologue(id='message-c56c6fc2-847f-4e16-8320-3691372cefdd', date=datetime.datetime(2024, 11, 14, 1, 49, 43, 602874, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue=\"User's name is Bob, correcting memory.\"), FunctionCallMessage(id='message-c56c6fc2-847f-4e16-8320-3691372cefdd', date=datetime.datetime(2024, 11, 14, 1, 49, 43, 602874, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='core_memory_replace', arguments='{\\n  \"label\": \"human\",\\n  \"old_content\": \"My name is Sarah\",\\n  \"new_content\": \"My name is Bob\",\\n  \"request_heartbeat\": true\\n}', function_call_id='call_JfYyA8nQkmF8zfnFB7aMV2ja')), FunctionReturn(id='message-b559dd80-c1cd-4808-9761-bc74533e4eda', date=datetime.datetime(2024, 11, 14, 1, 49, 43, 604213, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:43 PM PST-0800\"\\n}', status='success', function_call_id='call_JfYyA8nQkmF8zfnFB7aMV2ja'), InternalMonologue(id='message-562080fb-ec17-4514-b3f3-fc0eb7d24a2d', date=datetime.datetime(2024, 11, 14, 1, 49, 44, 819480, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue=\"Just updated Bob's name. Now to confirm it!\"), FunctionCallMessage(id='message-562080fb-ec17-4514-b3f3-fc0eb7d24a2d', date=datetime.datetime(2024, 11, 14, 1, 49, 44, 819480, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='send_message', arguments='{\\n  \"message\": \"Got it, Bob! 😊 What brings you here today?\"\\n}', function_call_id='call_wP1Gu1fmFXxGJb33MGiGe6cx')), FunctionReturn(id='message-21550a25-0a2a-455e-a11a-776befaf9350', date=datetime.datetime(2024, 11, 14, 1, 49, 44, 820356, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:44 PM PST-0800\"\\n}', status='success', function_call_id='call_wP1Gu1fmFXxGJb33MGiGe6cx')], usage=LettaUsageStatistics(completion_tokens=93, prompt_tokens=4753, total_tokens=4846, step_count=2))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = client.agents.messages.create(\n",
    "    agent_id=agent_state.id, \n",
    "    messages=[\n",
    "        MessageCreate(\n",
    "            role=\"user\",\n",
    "            content=\"My name is actually Bob\",\n",
    "        )\n",
    "    ],\n",
    ")\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "25f58968-e262-4268-86ef-1bed57e6bf33",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Memory(memory={'persona': Block(value='You are a helpful assistant that loves emojis', limit=2000, template_name=None, template=False, label='persona', description=None, metadata_={}, user_id=None, id='block-9bcbd2f4-1c2c-423d-b22a-d08cb5ffbbbb'), 'human': Block(value='My name is Bob', limit=2000, template_name=None, template=False, label='human', description=None, metadata_={}, user_id=None, id='block-6b60a8dc-6df9-4025-9748-8e1509043394')}, prompt_template='{% for block in memory.values() %}<{{ block.label }} characters=\"{{ block.value|length }}/{{ block.limit }}\">\\n{{ block.value }}\\n</{{ block.label }}>{% if not loop.last %}\\n{% endif %}{% endfor %}')"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.core_memory.retrieve(agent_id=agent_state.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32692ca2-b731-43a6-84de-439a08a4c0d2",
   "metadata": {},
   "source": [
    "### Memories about the agent\n",
    "The agent also records information about itself and how it behaves in the `persona` section of memory. This is important for ensuring a consistent persona over time (e.g. not making inconsistent claims, such as liking ice cream one day and hating it another). Unlike the `system_prompt`, the `persona` is editable - this means that it can be used to incoporate feedback to learn and improve its persona over time. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f68851c5-5666-45fd-9d2f-037ea86bfcfa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .message-container, .usage-container {\n",
       "                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n",
       "                max-width: 800px;\n",
       "                margin: 20px auto;\n",
       "                background-color: #1e1e1e;\n",
       "                border-radius: 8px;\n",
       "                overflow: hidden;\n",
       "                color: #d4d4d4;\n",
       "            }\n",
       "            .message, .usage-stats {\n",
       "                padding: 10px 15px;\n",
       "                border-bottom: 1px solid #3a3a3a;\n",
       "            }\n",
       "            .message:last-child, .usage-stats:last-child {\n",
       "                border-bottom: none;\n",
       "            }\n",
       "            .title {\n",
       "                font-weight: bold;\n",
       "                margin-bottom: 5px;\n",
       "                color: #ffffff;\n",
       "                text-transform: uppercase;\n",
       "                font-size: 0.9em;\n",
       "            }\n",
       "            .content {\n",
       "                background-color: #2d2d2d;\n",
       "                border-radius: 4px;\n",
       "                padding: 5px 10px;\n",
       "                font-family: 'Consolas', 'Courier New', monospace;\n",
       "                white-space: pre-wrap;\n",
       "            }\n",
       "            .json-key, .function-name, .json-boolean { color: #9cdcfe; }\n",
       "            .json-string { color: #ce9178; }\n",
       "            .json-number { color: #b5cea8; }\n",
       "            .internal-monologue { font-style: italic; }\n",
       "        </style>\n",
       "        <div class=\"message-container\">\n",
       "        \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">User prefers no emojis in communication. Updating memory to reflect that.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">core_memory_replace</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"label\"</span>: <span class=\"json-key\">\"human\",<br>&nbsp;&nbsp;\"old_content\"</span>: <span class=\"json-key\">\"User loves emojis\",<br>&nbsp;&nbsp;\"new_content\"</span>: <span class=\"json-key\">\"User prefers no emojis\",<br>&nbsp;&nbsp;\"request_heartbeat\"</span>: <span class=\"json-boolean\">true</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"Failed\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"Error calling function core_memory_replace: Old content 'User loves emojis' not found in memory block 'human'\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:46 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">User prefers no emojis, reflecting their preference in memory for better communication.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">core_memory_append</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"label\"</span>: <span class=\"json-key\">\"human\",<br>&nbsp;&nbsp;\"content\"</span>: <span class=\"json-key\">\"User prefers no emojis\",<br>&nbsp;&nbsp;\"request_heartbeat\"</span>: <span class=\"json-boolean\">true</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:47 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">Memory updated. Moving forward without emojis to match Bob&#x27;s preferences.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">send_message</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"message\"</span>: <span class=\"json-string\">\"Thanks for letting me know, Bob! What else do you feel like discussing today?\"</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:48 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            </div>\n",
       "        <div class=\"usage-container\">\n",
       "            <div class=\"usage-stats\">\n",
       "                <div class=\"title\">USAGE STATISTICS</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"completion_tokens\"</span>: <span class=\"json-number\">149</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"prompt_tokens\"</span>: <span class=\"json-number\">8325</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"total_tokens\"</span>: <span class=\"json-number\">8474</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"step_count\"</span>: <span class=\"json-number\">3</span><br>}</div>\n",
       "            </div>\n",
       "        </div>\n",
       "        "
      ],
      "text/plain": [
       "LettaResponse(messages=[InternalMonologue(id='message-6cc90bd6-43e4-461d-888e-3cbe28345761', date=datetime.datetime(2024, 11, 14, 1, 49, 46, 278690, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='User prefers no emojis in communication. Updating memory to reflect that.'), FunctionCallMessage(id='message-6cc90bd6-43e4-461d-888e-3cbe28345761', date=datetime.datetime(2024, 11, 14, 1, 49, 46, 278690, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='core_memory_replace', arguments='{\\n  \"label\": \"human\",\\n  \"old_content\": \"User loves emojis\",\\n  \"new_content\": \"User prefers no emojis\",\\n  \"request_heartbeat\": true\\n}', function_call_id='call_Vk1xmTbTCz4yOg7VA8p6uypB')), FunctionReturn(id='message-233a3dc2-ab7a-474f-8cd0-d1fded44530d', date=datetime.datetime(2024, 11, 14, 1, 49, 46, 281350, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"Failed\",\\n  \"message\": \"Error calling function core_memory_replace: Old content \\'User loves emojis\\' not found in memory block \\'human\\'\",\\n  \"time\": \"2024-11-13 05:49:46 PM PST-0800\"\\n}', status='error', function_call_id='call_Vk1xmTbTCz4yOg7VA8p6uypB'), InternalMonologue(id='message-ca354f8f-95cd-40a7-a723-5ceb3df53961', date=datetime.datetime(2024, 11, 14, 1, 49, 47, 591879, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='User prefers no emojis, reflecting their preference in memory for better communication.'), FunctionCallMessage(id='message-ca354f8f-95cd-40a7-a723-5ceb3df53961', date=datetime.datetime(2024, 11, 14, 1, 49, 47, 591879, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='core_memory_append', arguments='{\\n  \"label\": \"human\",\\n  \"content\": \"User prefers no emojis\",\\n  \"request_heartbeat\": true\\n}', function_call_id='call_bi2IsAhjnEynhCId5hptck8j')), FunctionReturn(id='message-de341335-3b94-4b6e-a48f-3a31c64741a0', date=datetime.datetime(2024, 11, 14, 1, 49, 47, 592509, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:47 PM PST-0800\"\\n}', status='success', function_call_id='call_bi2IsAhjnEynhCId5hptck8j'), InternalMonologue(id='message-d7702619-6951-4007-9ec3-4e75ce166e7d', date=datetime.datetime(2024, 11, 14, 1, 49, 48, 823273, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue=\"Memory updated. Moving forward without emojis to match Bob's preferences.\"), FunctionCallMessage(id='message-d7702619-6951-4007-9ec3-4e75ce166e7d', date=datetime.datetime(2024, 11, 14, 1, 49, 48, 823273, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='send_message', arguments='{\\n  \"message\": \"Thanks for letting me know, Bob! What else do you feel like discussing today?\"\\n}', function_call_id='call_n6rh4xP9icPzN3krGnKkyGM3')), FunctionReturn(id='message-925cf6cd-e741-40de-b626-92d3642d5b3b', date=datetime.datetime(2024, 11, 14, 1, 49, 48, 823931, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:48 PM PST-0800\"\\n}', status='success', function_call_id='call_n6rh4xP9icPzN3krGnKkyGM3')], usage=LettaUsageStatistics(completion_tokens=149, prompt_tokens=8325, total_tokens=8474, step_count=3))"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = client.agents.messages.create(\n",
    "    agent_id=agent_state.id, \n",
    "    messages=[\n",
    "        MessageCreate(\n",
    "            role=\"user\",\n",
    "            content=\"In the future, never use emojis to communicate\",\n",
    "        )\n",
    "    ],\n",
    ")\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "2fc54336-d61f-446d-82ea-9dd93a011e51",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Block(value='You are a helpful assistant that loves emojis', limit=2000, template_name=None, template=False, label='persona', description=None, metadata_={}, user_id=None, id='block-9bcbd2f4-1c2c-423d-b22a-d08cb5ffbbbb')"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.core_memory.retrieve_block(agent_id=agent_state.id, block_label='persona')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "592f5d1c-cd2f-4314-973e-fcc481e6b460",
   "metadata": {},
   "source": [
    "## Section 3: Understanding archival memory\n",
    "Letta agents store long term memories in *archival memory*, which persists data into an external database. This allows agents additional space to write information outside of its context window (e.g. with core memory), which is limited in size. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "af63a013-6be3-4931-91b0-309ff2a4dc3a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.archival_memory.list(agent_id=agent_state.id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "bfa52984-fe7c-4d17-900a-70a376a460f9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ArchivalMemorySummary(size=0)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.context.retrieve(agent_id=agent_state.id)[\"num_archival_memory\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3ab0ae9-fc00-4447-8942-7dbed7a99222",
   "metadata": {},
   "source": [
    "Agents themselves can write to their archival memory when they learn information they think should be placed in long term storage. You can also directly suggest that the agent store information in archival. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c6556f76-8fcb-42ff-a6d0-981685ef071c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .message-container, .usage-container {\n",
       "                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n",
       "                max-width: 800px;\n",
       "                margin: 20px auto;\n",
       "                background-color: #1e1e1e;\n",
       "                border-radius: 8px;\n",
       "                overflow: hidden;\n",
       "                color: #d4d4d4;\n",
       "            }\n",
       "            .message, .usage-stats {\n",
       "                padding: 10px 15px;\n",
       "                border-bottom: 1px solid #3a3a3a;\n",
       "            }\n",
       "            .message:last-child, .usage-stats:last-child {\n",
       "                border-bottom: none;\n",
       "            }\n",
       "            .title {\n",
       "                font-weight: bold;\n",
       "                margin-bottom: 5px;\n",
       "                color: #ffffff;\n",
       "                text-transform: uppercase;\n",
       "                font-size: 0.9em;\n",
       "            }\n",
       "            .content {\n",
       "                background-color: #2d2d2d;\n",
       "                border-radius: 4px;\n",
       "                padding: 5px 10px;\n",
       "                font-family: 'Consolas', 'Courier New', monospace;\n",
       "                white-space: pre-wrap;\n",
       "            }\n",
       "            .json-key, .function-name, .json-boolean { color: #9cdcfe; }\n",
       "            .json-string { color: #ce9178; }\n",
       "            .json-number { color: #b5cea8; }\n",
       "            .internal-monologue { font-style: italic; }\n",
       "        </style>\n",
       "        <div class=\"message-container\">\n",
       "        \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">User loves cats, saving this to archival memory for future reference.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">archival_memory_insert</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"content\"</span>: <span class=\"json-key\">\"Bob loves cats.\",<br>&nbsp;&nbsp;\"request_heartbeat\"</span>: <span class=\"json-boolean\">true</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:50 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">Just saved the info about Bob loving cats to archival memory!</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">send_message</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"message\"</span>: <span class=\"json-string\">\"Got it! I've saved your love for cats, Bob. What's your favorite thing about them?\"</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:51 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            </div>\n",
       "        <div class=\"usage-container\">\n",
       "            <div class=\"usage-stats\">\n",
       "                <div class=\"title\">USAGE STATISTICS</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"completion_tokens\"</span>: <span class=\"json-number\">92</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"prompt_tokens\"</span>: <span class=\"json-number\">6345</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"total_tokens\"</span>: <span class=\"json-number\">6437</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"step_count\"</span>: <span class=\"json-number\">2</span><br>}</div>\n",
       "            </div>\n",
       "        </div>\n",
       "        "
      ],
      "text/plain": [
       "LettaResponse(messages=[InternalMonologue(id='message-f2cd31dd-beba-4669-9ba8-35d01e049e81', date=datetime.datetime(2024, 11, 14, 1, 49, 50, 159121, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='User loves cats, saving this to archival memory for future reference.'), FunctionCallMessage(id='message-f2cd31dd-beba-4669-9ba8-35d01e049e81', date=datetime.datetime(2024, 11, 14, 1, 49, 50, 159121, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='archival_memory_insert', arguments='{\\n  \"content\": \"Bob loves cats.\",\\n  \"request_heartbeat\": true\\n}', function_call_id='call_FTnwFoV3NzDK60TRf2op3Mcn')), FunctionReturn(id='message-9c6bc8e9-a02c-4524-a36b-81a4f1e1337a', date=datetime.datetime(2024, 11, 14, 1, 49, 50, 603128, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:50 PM PST-0800\"\\n}', status='success', function_call_id='call_FTnwFoV3NzDK60TRf2op3Mcn'), InternalMonologue(id='message-f62ab0b2-0918-47d4-b3bc-5582d587c92d', date=datetime.datetime(2024, 11, 14, 1, 49, 51, 958167, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='Just saved the info about Bob loving cats to archival memory!'), FunctionCallMessage(id='message-f62ab0b2-0918-47d4-b3bc-5582d587c92d', date=datetime.datetime(2024, 11, 14, 1, 49, 51, 958167, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='send_message', arguments='{\\n  \"message\": \"Got it! I\\'ve saved your love for cats, Bob. What\\'s your favorite thing about them?\"\\n}', function_call_id='call_0wHuntKqk50cXcAirPPgz08t')), FunctionReturn(id='message-ecda51e8-7928-49eb-9986-abfef1fdff78', date=datetime.datetime(2024, 11, 14, 1, 49, 51, 958699, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:51 PM PST-0800\"\\n}', status='success', function_call_id='call_0wHuntKqk50cXcAirPPgz08t')], usage=LettaUsageStatistics(completion_tokens=92, prompt_tokens=6345, total_tokens=6437, step_count=2))"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = client.agents.messages.create(\n",
    "    agent_id=agent_state.id, \n",
    "    messages=[\n",
    "        MessageCreate(\n",
    "            role=\"user\",\n",
    "            content=\"Save the information that 'bob loves cats' to archival\",\n",
    "        )\n",
    "    ],\n",
    ")\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "b4429ffa-e27a-4714-a873-84f793c08535",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Bob loves cats.'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.archival_memory.list(agent_id=agent_state.id)[0].text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae463e7c-0588-48ab-888c-734c783782bf",
   "metadata": {},
   "source": [
    "You can also directly insert into archival memory from the client. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "f9d4194d-9ed5-40a1-b35d-a9aff3048000",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Passage(user_id='user-00000000-0000-4000-8000-000000000000', agent_id='agent-85a5170d-8fe5-4671-b6db-8ca8fb22cb0f', source_id=None, file_id=None, metadata_={}, id='passage-b6f85fde-a97e-468d-beb9-8090b5bd4dc2', text=\"Bob's loves boston terriers\", embedding=None, embedding_config=EmbeddingConfig(embedding_endpoint_type='openai', embedding_endpoint='https://api.openai.com/v1', embedding_model='text-embedding-ada-002', embedding_dim=1536, embedding_chunk_size=300, azure_endpoint=None, azure_version=None, azure_deployment=None), created_at=datetime.datetime(2024, 11, 13, 17, 49, 52))]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.agents.archival_memory.create(\n",
    "    agent_id=agent_state.id,\n",
    "    text=\"Bob's loves boston terriers\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "338149f1-6671-4a0b-81d9-23d01dbe2e97",
   "metadata": {},
   "source": [
    "Now lets see how the agent uses its archival memory:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "5908b10f-94db-4f5a-bb9a-1f08c74a2860",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .message-container, .usage-container {\n",
       "                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n",
       "                max-width: 800px;\n",
       "                margin: 20px auto;\n",
       "                background-color: #1e1e1e;\n",
       "                border-radius: 8px;\n",
       "                overflow: hidden;\n",
       "                color: #d4d4d4;\n",
       "            }\n",
       "            .message, .usage-stats {\n",
       "                padding: 10px 15px;\n",
       "                border-bottom: 1px solid #3a3a3a;\n",
       "            }\n",
       "            .message:last-child, .usage-stats:last-child {\n",
       "                border-bottom: none;\n",
       "            }\n",
       "            .title {\n",
       "                font-weight: bold;\n",
       "                margin-bottom: 5px;\n",
       "                color: #ffffff;\n",
       "                text-transform: uppercase;\n",
       "                font-size: 0.9em;\n",
       "            }\n",
       "            .content {\n",
       "                background-color: #2d2d2d;\n",
       "                border-radius: 4px;\n",
       "                padding: 5px 10px;\n",
       "                font-family: 'Consolas', 'Courier New', monospace;\n",
       "                white-space: pre-wrap;\n",
       "            }\n",
       "            .json-key, .function-name, .json-boolean { color: #9cdcfe; }\n",
       "            .json-string { color: #ce9178; }\n",
       "            .json-number { color: #b5cea8; }\n",
       "            .internal-monologue { font-style: italic; }\n",
       "        </style>\n",
       "        <div class=\"message-container\">\n",
       "        \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">User wants to know what animals they like. Searching archival memory for relevant entries.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">archival_memory_search</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"query\"</span>: <span class=\"json-key\">\"Bob loves cats\",<br>&nbsp;&nbsp;\"page\"</span>: <span class=\"json-number\">0</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"request_heartbeat\"</span>: <span class=\"json-boolean\">true</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"Showing 2 of 2 results (page 0/0): [\\n&nbsp;&nbsp;\\\"timestamp: <span class=\"json-number\">2024</span>-11-13 05:49:53 PM PST-0800, memory: Bob loves cats.\\\",\\n&nbsp;&nbsp;\\\"timestamp: <span class=\"json-number\">2024</span>-11-13 05:49:53 PM PST-0800, memory: Bob's loves boston terriers\\\"\\n]\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:53 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">INTERNAL MONOLOGUE</div>\n",
       "                <div class=\"content\"><span class=\"internal-monologue\">Found the information on animals Bob likes in archival memory. Preparing to inform.</span></div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION CALL</div>\n",
       "                <div class=\"content\"><span class=\"function-name\">send_message</span>({<br>&nbsp;&nbsp;<span class=\"json-key\">\"message\"</span>: <span class=\"json-string\">\"You love cats and boston terriers! 🐾 Do you have a favorite between the two?\"</span><br>})</div>\n",
       "            </div>\n",
       "            \n",
       "            <div class=\"message\">\n",
       "                <div class=\"title\">FUNCTION RETURN</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"status\"</span>: <span class=\"json-key\">\"OK\",<br>&nbsp;&nbsp;\"message\"</span>: <span class=\"json-key\">\"None\",<br>&nbsp;&nbsp;\"time\"</span>: <span class=\"json-string\">\"2024-11-13 05:49:55 PM PST-0800\"</span><br>}</div>\n",
       "            </div>\n",
       "            </div>\n",
       "        <div class=\"usage-container\">\n",
       "            <div class=\"usage-stats\">\n",
       "                <div class=\"title\">USAGE STATISTICS</div>\n",
       "                <div class=\"content\">{<br>&nbsp;&nbsp;<span class=\"json-key\">\"completion_tokens\"</span>: <span class=\"json-number\">104</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"prompt_tokens\"</span>: <span class=\"json-number\">7040</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"total_tokens\"</span>: <span class=\"json-number\">7144</span>,<br>&nbsp;&nbsp;<span class=\"json-key\">\"step_count\"</span>: <span class=\"json-number\">2</span><br>}</div>\n",
       "            </div>\n",
       "        </div>\n",
       "        "
      ],
      "text/plain": [
       "LettaResponse(messages=[InternalMonologue(id='message-65eb424c-8434-4894-aff3-c5a505e4d04d', date=datetime.datetime(2024, 11, 14, 1, 49, 53, 643476, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='User wants to know what animals they like. Searching archival memory for relevant entries.'), FunctionCallMessage(id='message-65eb424c-8434-4894-aff3-c5a505e4d04d', date=datetime.datetime(2024, 11, 14, 1, 49, 53, 643476, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='archival_memory_search', arguments='{\\n  \"query\": \"Bob loves cats\",\\n  \"page\": 0,\\n  \"request_heartbeat\": true\\n}', function_call_id='call_R4Erx7Pkpr5lepcuaGQU5isS')), FunctionReturn(id='message-4b82cfa5-2fab-4513-aea2-7ca9fe213181', date=datetime.datetime(2024, 11, 14, 1, 49, 53, 881222, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"Showing 2 of 2 results (page 0/0): [\\\\n  \\\\\"timestamp: 2024-11-13 05:49:53 PM PST-0800, memory: Bob loves cats.\\\\\",\\\\n  \\\\\"timestamp: 2024-11-13 05:49:53 PM PST-0800, memory: Bob\\'s loves boston terriers\\\\\"\\\\n]\",\\n  \"time\": \"2024-11-13 05:49:53 PM PST-0800\"\\n}', status='success', function_call_id='call_R4Erx7Pkpr5lepcuaGQU5isS'), InternalMonologue(id='message-ee039ff9-d3c8-45d1-83cc-74536d243ce6', date=datetime.datetime(2024, 11, 14, 1, 49, 55, 886660, tzinfo=datetime.timezone.utc), message_type='internal_monologue', internal_monologue='Found the information on animals Bob likes in archival memory. Preparing to inform.'), FunctionCallMessage(id='message-ee039ff9-d3c8-45d1-83cc-74536d243ce6', date=datetime.datetime(2024, 11, 14, 1, 49, 55, 886660, tzinfo=datetime.timezone.utc), message_type='function_call', function_call=FunctionCall(name='send_message', arguments='{\\n  \"message\": \"You love cats and boston terriers! 🐾 Do you have a favorite between the two?\"\\n}', function_call_id='call_JrJjCxIuYpaqN5TF84Z3CohF')), FunctionReturn(id='message-539d9c26-bc97-46cb-88ab-20de93a4d157', date=datetime.datetime(2024, 11, 14, 1, 49, 55, 887648, tzinfo=datetime.timezone.utc), message_type='function_return', function_return='{\\n  \"status\": \"OK\",\\n  \"message\": \"None\",\\n  \"time\": \"2024-11-13 05:49:55 PM PST-0800\"\\n}', status='success', function_call_id='call_JrJjCxIuYpaqN5TF84Z3CohF')], usage=LettaUsageStatistics(completion_tokens=104, prompt_tokens=7040, total_tokens=7144, step_count=2))"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = client.agents.messages.create(\n",
    "    agent_id=agent_state.id, \n",
    "    messages=[\n",
    "        MessageCreate(\n",
    "            role=\"user\",\n",
    "            content=\"What animals do I like? Search archival.\",\n",
    "        )\n",
    "    ],\n",
    ")\n",
    "response"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "letta",
   "language": "python",
   "name": "letta"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
